package dbu.dbase;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import dbu.dbase.charset.MIKCharset;

public class DBaseRecord extends DBaseStructure {

	public static final byte EOF = 0x1A;
	public static final byte SPACE = 0x20;
	public static final byte ASTERISK = 0x2A;

	private DBaseHeader header;
	private byte[] record; 

	public DBaseRecord(DBaseHeader header) {
		this.header = header;
		record = new byte[header.getNumberOfBytesInTheRecord()];
	}

	@Override
	protected int read(InputStream stream) throws IOException {
		stream.read(record);
		if (record[0] == EOF) {
			return 1;
		}
		return header.getNumberOfBytesInTheRecord();
	}

	protected int getOffset(int index) {
		int offset = 1;
		for (int i = 0; i < index; i++) {
			offset += header.getFieldLength(i);
		}
		return offset;
	}

	public Object get(int i) {
		int from = getOffset(i);
		int to = from + header.getFieldLength(i);
		byte[] buff = Arrays.copyOfRange(record, from, to);
		switch (header.getFieldType(i)) {
			case Character:
				/** All OEM code page characters. */
				return new String(buff, new MIKCharset());
			case Date:
				/** Numbers and a character to separate month, day, and year (stored internally as 8 digits in YYYYMMDD format). */
				// TODO
				return new String(buff);
			case Numeric:
				/** - . 0 1 2 3 4 5 6 7 8 9 */
				// TODO
				return new String(buff);
			case Logical:
				/** ? Y y N n T t F f (? when not initialized). */
				// TODO
				return new String(buff);
			case Memo:
				/**All OEM code page characters (stored internally as 10 digits representing a .DBT block number). */
				// TODO
				return new String(buff, new MIKCharset());
		}
		return null;
	}

	@Override
	public String toString() {
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < header.getNumOfFields(); i++) {
			result.append(get(i));
		}
		return result.toString();
	}
}
